<template>
  <view class="container">
    <Loading :show="isLoading" />
    
    <!-- 设备信息卡片 -->
    <view class="device-info-card" :class="getDeviceCardClass(deviceInfo.status)">
      <view class="device-header">
        <image 
          class="device-icon" 
          :src="deviceInfo.imgUrl || '/static/device-icon.png'" 
          mode="aspectFit" 
          @error="onImageError"
        />
        <view class="device-title">
          <text class="device-name">{{ deviceInfo.deviceName || '智能售货机' }}</text>
          <view class="status-row">
            <text class="device-status" :class="getStatusClass(deviceInfo.status)">
              {{ getStatusText(deviceInfo.status) }}
            </text>
            <text class="device-type-tag" v-if="deviceInfo.deviceType?.typeName">
              {{ deviceInfo.deviceType.typeName }}
            </text>
          </view>
        </view>
      </view>
      
      <!-- 设备位置信息 -->
      <view class="location-info" v-if="deviceInfo.location">
        <view class="location-header">
          <text class="location-icon">📍</text>
          <text class="location-title">设备位置</text>
        </view>
        <text class="location-address">{{ deviceInfo.location.address || '位置信息' }}</text>
      </view>
    
    </view>

    <!-- 商品列表标题 -->
    <view class="section-header">
      <text class="section-title">商品</text>
      <text class="product-count">共 {{ products.length }} 种商品</text>
    </view>

    <!-- 商品列表 -->
    <view class="product-list">
      <view v-if="products.length === 0 && !isLoading" class="empty-state">
        <image src="/static/empty.png" mode="aspectFit" class="empty-image" />
        <text class="empty-text">暂无商品</text>
      </view>

      <view v-else class="products-container">
        <view
          v-for="product in products"
          :key="product.id"
          class="product-item"
          @click="navigateToDetail(product)"
        >
          <view :class="['product-item-content', getProductCardClass(product)]">
            <image
              class="product-image"
              :src="product.mainImage || product.image"
              mode="aspectFill"
              lazy-load
              @error="onProductImageError"
            />
            <view class="product-info">
              <text class="product-name">{{ product.name }}</text>
              <view class="product-price-row">
                <text class="product-price">¥{{ product.price }}</text>
                <text
                  class="product-original-price"
                  v-if="product.originalPrice"
                >¥{{ product.originalPrice }}</text>
              </view>
              <view class="product-meta">
                <view class="meta-row">
                  <text :class="['stock-info', getStockClass(product.stock)]">
                    库存: {{ product.stock || 0 }}
                  </text>
                  <text class="channel-info">通道: {{ product.channelPosition || '--' }}</text>
                </view>
                <view class="tag-row">
                  <text v-if="product.isHot" class="hot-tag">热销</text>
                  <text v-if="isLowStock(product)" class="low-stock-tag">低库存</text>
                </view>
              </view>
            </view>
            <view class="product-actions">
              <view class="quantity-controls">
                <button class="quantity-btn minus-btn" 
                        :disabled="deviceInfo.status !== 2 || !isInCart(product.id, product.channelId) || getCartItemQuantity(product.id, product.channelId) <= 0"
                        @click.stop="updateCartQuantity(product.id, product.channelId, getCartItemQuantity(product.id, product.channelId) - 1)">
                  <text class="btn-text">-</text>
                </button>
                <text class="quantity-display" v-if="isInCart(product.id, product.channelId)">
                  {{ getCartItemQuantity(product.id, product.channelId) }}
                </text>
                <text class="quantity-display" v-else>0</text>
                <button class="quantity-btn plus-btn" 
                        :disabled="deviceInfo.status !== 2 || product.stock <= 0 || getCartItemQuantity(product.id, product.channelId) >= product.stock"
                        @click.stop="addToCart(product)">
                  <text class="btn-text">+</text>
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="action-buttons">
        <text class="cart-count" v-if="cartCount > 0">{{ cartCount }}</text>
        <button 
          class="cart-toggle-btn"
          @click="toggleCart"
        >
        
          <text class="cart-icon">🛒</text>
          
        </button>
        <button 
          class="coupon-btn"
          @click="showCouponSelector"
          v-if="cartItems.length > 0"
        >
          <text class="coupon-icon">🎟️</text>
          <text class="coupon-text">
            {{ selectedCoupon ? `已优惠¥${(originalCartTotal - cartTotal).toFixed(2)}` : '选择优惠券' }}
          </text>
        </button>
        <button 
          :class="['buy-now-btn', getBuyButtonClass()]"
          @click="buyNow()"
          :disabled="!canBuy()"
        >
          {{ getBuyButtonText() }}
        </button>
      </view>
    </view>

    <!-- 购物车弹窗 -->
    <view class="cart-modal" v-if="showCart" @click="toggleCart">
      <view class="cart-content" @click.stop>
        <view class="cart-header">
          <text class="cart-title">购物车</text>
          <button class="close-btn" @click="toggleCart">×</button>
        </view>
        
        <view class="cart-items" v-if="cartItems.length > 0">
          <view class="cart-item" v-for="item in cartItems" :key="item.id">
            <image class="cart-item-image" :src="item.mainImage" mode="aspectFill" />
            <view class="cart-item-info">
              <text class="cart-item-name">{{ item.name }}</text>
              <text class="cart-item-price">¥{{ item.price }}</text>
            </view>
            <view class="cart-item-actions">
              <button class="quantity-btn" @click="updateCartQuantity(item.id, item.channelId, item.quantity - 1)">-</button>
              <text class="quantity-text">{{ item.quantity }}</text>
              <button class="quantity-btn" @click="updateCartQuantity(item.id, item.channelId, item.quantity + 1)">+</button>
              <button class="remove-btn" @click="removeFromCart(item.id, item.channelId)">
                <img src="/static/icons/delete.svg" class="remove-icon" />
              </button>
            </view>
          </view>
        </view>
        
        <view class="cart-empty" v-else>
          <text class="empty-text">购物车为空</text>
        </view>
        
        <view class="cart-footer" v-if="cartItems.length > 0">
          <view class="cart-total">
            <text class="total-label">总计:</text>
            <text class="total-price">¥{{ cartTotal.toFixed(2) }}</text>
          </view>
          <view class="cart-actions">
            <button class="clear-btn" @click="clearCart">清空</button>
            <button class="buy-cart-btn" @click="buyFromCart">结算</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <view class="coupon-modal" v-if="showCouponModal" @click="cancelCoupon">
      <view class="coupon-content" @click.stop>
        <view class="coupon-header">
          <text class="coupon-title">选择优惠券</text>
          <button class="close-btn" @click="cancelCoupon">×</button>
        </view>
        
        <view class="coupon-list" v-if="!isLoadingCoupons">
          <view 
            v-for="coupon in coupons" 
            :key="coupon.id"
            class="coupon-item"
            :class="{ 
              'coupon-disabled': !isCouponAvailable(coupon, originalCartTotal.value),
              'coupon-selected': selectedCoupon?.id === coupon.id
            }"
            @click="selectCoupon(coupon)"
          >
            <view class="coupon-info">
              <view class="coupon-header-row">
                <text class="coupon-name">{{ coupon.couponName || '优惠券' }}</text>
                <text class="coupon-type">{{ getCouponTypeName(coupon.coupon.type) }}</text>
              </view>
              <view class="coupon-value">
                <text class="value-text">{{ getCouponDescription(coupon) }}</text>
                <text class="min-point" v-if="coupon.coupon.minPoint">满{{ coupon.coupon.minPoint }}元可用</text>
              </view>
              <view class="coupon-scope">
                <text class="scope-text">{{ getCouponScopeDescription(coupon) }}</text>
              </view>
              <view class="coupon-time-info">
                <text class="coupon-get-time">领取时间：{{ formatDate(coupon.getTime) }}</text>
                <text class="coupon-expire-time">有效期至：{{ formatDate(coupon.expireTime) }}</text>
              </view>
            </view>
            <view class="coupon-status">
              <text class="status-text">{{ getCouponStatusName(coupon.status) }}</text>
            </view>
          </view>
          
          <view v-if="coupons.length === 0" class="empty-coupons">
            <text class="empty-text">暂无可用优惠券</text>
          </view>
        </view>
        
        <view v-else class="loading-coupons">
          <Loading :show="true" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import Loading from "@/components/Loading.vue";
import { getInfoByNo } from "@/api/device";
import { getProductDetail } from "@/api/product";
import { getUserCouponList } from '@/api/coupon/user';
import { createOrder, createOrderCoupon } from '@/api/order/index';
import { updateUserCoupon } from '@/api/coupon/user';
import { checkStock } from '@/api/device';
import type { DeviceVO } from "@/api/device/types";

// 修改优惠券接口定义
interface Coupon {
  id: number;
  couponId: number;
  couponCode: string;
  couponName: string;
  status: number;
  statusName: string | null;
  getType: number;
  getTypeName: string | null;
  getTime: string;
  useTime: string | null;
  expireTime: string;
  orderNo: string | null;
  userId: number;
  userName: string | null;
  createTime: string;
  updateTime: string;
  // 优惠券详细信息
  coupon: {
    id: number;
    code: string;
    name: string;
    type: number; // 1:满减券,2:折扣券,3:立减券
    discount: number; // 优惠金额/折扣率
    minPoint: number; // 最低消费金额
    useScope: number; // 使用范围(0:全场通用,1:指定品类,2:指定商品)
    scopeId: string; // 范围ID(品类ID或商品ID，多个以逗号分隔)
    startTime: string | null;
    endTime: string | null;
    status: number;
  };
}

// 扩展设备信息接口
interface ExtendedDeviceVO extends DeviceVO {
  imgUrl?: string;
  deviceType?: {
    typeName: string;
  };
  deviceChannel?: Array<{
    id: number;
    channelPosition: string;
    status: number;
  }>;
  sn?: string;
  location?: {
    lat: number;
    lon: number;
    distance?: number;
    address?: string;
  };
  // 设备库存信息
  deviceStock?: Array<{
    id: number;
    productId: number;
    productName?: string;
    stockQuantity: number;
    stock?: number;
    quantity?: number;
    price?: number;
    originalPrice?: number;
    mainImage?: string;
    image?: string;
    isHot?: number;
    description?: string;
    channelId: number;
    channelPosition: string;
  }>;
}

// 库存信息接口
interface StockItem {
  id: number;
  productId: number;
  productName?: string;
  stock: number;
  quantity?: number;
  price?: number;
  originalPrice?: number;
  mainImage?: string;
  image?: string;
  isHot?: number;
  description?: string;
  channelId: number;
  channelPosition: string;
}

// 商品详情接口
interface ProductDetail {
  id: number;
  name: string;
  price: string;
  originalPrice: string;
  productNo: string;
  status: number;
  sort: number;
  brandId?: number;
  brandName?: string;
  categoryId?: number;
  categoryName?: string;
  createTime: string;
  updateTime: string;
  productDetail?: {
    id: number;
    description: string;
    mainImage: string;
    subImages: string;
    sales: number;
    isHot?: number;
    isHotName?: string;
    subtitle?: string;
    volume?: string;
    createTime: string;
    updateTime: string;
  };
}

// 购物车商品接口
interface CartItem {
  id: number;
  name: string;
  price: number;
  mainImage: string;
  stock: number;
  quantity: number;
  channelId: number;
  channelPosition: string;
}

// 合并后的商品信息接口
interface Product {
  id: number;
  name: string;
  price: number;
  originalPrice: number;
  mainImage: string;
  image: string;
  stock: number;
  isHot: number;
  description: string;
  sales?: number;
  subImages?: string[];
  channelId: number;
  channelPosition: string;
  categoryId?: number;
  categoryName?: string;
  channelNo?: number;
}

// API响应类型
interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data?: T;
  rows?: T[];
  total?: number;
}

// 响应式数据
const isLoading = ref(false);
const deviceNo = ref('');
const deviceInfo = ref<ExtendedDeviceVO>({
  id: 0,
  deviceName: '',
  deviceNo: '',
  model: '',
  status: 1,
  channelCount: 0,
  createTime: '',
  updateTime: ''
});
const products = ref<Product[]>([]);
const cartItems = ref<CartItem[]>([]); // 购物车商品
const showCart = ref(false); // 是否显示购物车
const showCouponModal = ref(false);
const coupons = ref<Coupon[]>([]);
const selectedCoupon = ref<Coupon | null>(null);
const isLoadingCoupons = ref(false);

// 购物车本地存储 key
const CART_STORAGE_KEY = 'device_cart_items';

// 购物车存储结构接口
interface CartStorage {
  deviceNo: string;
  items: CartItem[];
  selectedCoupon: Coupon | null;
}

// 读取本地购物车
const loadCartFromStorage = () => {
  try {
    const localCart = uni.getStorageSync(CART_STORAGE_KEY);
    if (localCart) {
      const cartData: CartStorage = JSON.parse(localCart);
      // 检查是否是同一设备的购物车
      if (cartData.deviceNo === deviceNo.value) {
        cartItems.value = cartData.items;
        selectedCoupon.value = cartData.selectedCoupon;
      } else {
        // 如果不是同一设备，清空购物车
        cartItems.value = [];
        selectedCoupon.value = null;
      }
    }
  } catch (e) {
    cartItems.value = [];
    selectedCoupon.value = null;
  }
};

// 存储购物车到本地
const saveCartToStorage = () => {
  const cartData: CartStorage = {
    deviceNo: deviceNo.value,
    items: cartItems.value,
    selectedCoupon: selectedCoupon.value
  };
  uni.setStorageSync(CART_STORAGE_KEY, JSON.stringify(cartData));
};

// 计算属性
const loadMoreStatus = computed(() => {
  if (isLoading.value) return "loading";
  return "noMore"; // 由于使用设备信息中的库存，不需要分页
});

// 购物车相关计算属性
const originalCartTotal = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0);
});

const cartTotal = computed(() => {
  return calculateDiscountedPrice(originalCartTotal.value, selectedCoupon.value);
});

const cartCount = computed(() => {
  return cartItems.value.reduce((count, item) => count + item.quantity, 0);
});

// 检查商品是否在购物车中
const isInCart = (productId: number, channelId: number) => {
  return cartItems.value.some(item => item.id === productId && item.channelId === channelId);
};

// 获取购物车中商品的数量
const getCartItemQuantity = (productId: number, channelId: number) => {
  const item = cartItems.value.find(item => item.id === productId && item.channelId === channelId);
  return item ? item.quantity : 0;
};

// 获取设备信息
const getDeviceInfo = async () => {
  try {
    isLoading.value = true;
    
    const res = await getInfoByNo(deviceNo.value) as ApiResponse<ExtendedDeviceVO>;
    
    if (res.code === 200 && res.data) {
      deviceInfo.value = res.data;
      
      // 获取设备信息后，立即处理库存商品
      await processDeviceStock();
    } else {
	  if (res.data == null) {
		uni.navigateBack();
		return null;
	  }
      console.error('获取设备信息失败：', res);
      uni.showToast({
        title: res.msg || '获取设备信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error("获取设备信息异常：", error);
    uni.showToast({
      title: '获取设备信息失败',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 根据商品ID获取商品详情
const getProductDetailById = async (productId: number): Promise<ProductDetail | null> => {
  try {
    const res = await getProductDetail(productId) as ApiResponse<ProductDetail>;
    if (res.code === 200 && res.data) {
      return res.data;
    }
    return null;
  } catch (error) {
    console.error(`获取商品详情失败，商品ID: ${productId}`, error);
    return null;
  }
};

// 处理设备库存信息
const processDeviceStock = async () => {
  if (!deviceInfo.value.deviceStock || deviceInfo.value.deviceStock.length === 0) {
    console.log('设备无库存信息');
    products.value = [];
    return;
  }

  // 获取所有商品的详情信息
  const productPromises = deviceInfo.value.deviceStock.map(async (stockItem: StockItem) => {
    const productDetail = await getProductDetailById(stockItem.productId);
    
    // 从设备通道信息中获取通道位置
    const channelInfo = deviceInfo.value.deviceChannel?.find(
      channel => channel.id === stockItem.channelId
    );
    // 合并库存信息和商品详情信息
    const mergedProduct: Product = {
      id: stockItem.productId,
      name: productDetail?.name || stockItem.productName || '未知商品',
      price: productDetail?.price ? parseFloat(productDetail.price) : (stockItem.price || 0),
      originalPrice: productDetail?.originalPrice ? parseFloat(productDetail.originalPrice) : (stockItem.originalPrice || 0),
      mainImage: productDetail?.productDetail?.mainImage || stockItem.mainImage || stockItem.image || '',
      image: stockItem.image || productDetail?.productDetail?.mainImage || stockItem.mainImage || '',
      stock: stockItem.stockQuantity || stockItem.stock || stockItem.quantity || 0,
      isHot: productDetail?.productDetail?.isHot || stockItem.isHot || 0,
      description: productDetail?.productDetail?.description || stockItem.description || '',
      sales: productDetail?.productDetail?.sales,
      subImages: productDetail?.productDetail?.subImages ? productDetail.productDetail.subImages.split(',').filter(img => img.trim()) : [],
      channelId: stockItem.channelId,
      channelPosition: channelInfo?.channelPosition || `通道${stockItem.channelId}`,
      categoryId: productDetail?.categoryId,
      categoryName: productDetail?.categoryName,
      channelNo: channelInfo?.channelNo
    };
    
    return mergedProduct;
  });
  
  // 等待所有商品详情获取完成
  const newProducts = await Promise.all(productPromises);
  
  products.value = newProducts;
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '--';
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (error) {
    return dateString;
  }
};

// 格式化日期时间
const formatDateTime = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-unused';
    case 1: return 'status-offline';
    case 2: return 'status-online';
    case 3: return 'status-error';
    case 4: return 'status-maintenance';
    case 5: return 'status-pending';
    default: return 'status-unused';
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '未使用';
    case 1: return '离线';
    case 2: return '在线';
    case 3: return '故障';
    case 4: return '维护中';
    case 5: return '待维护';
    default: return '未知';
  }
};

// 获取在线状态样式类
const getOnlineClass = (isOnline: boolean) => {
  return isOnline ? 'online' : 'offline';
};

// 获取库存样式类
const getStockClass = (stock: number) => {
  if (stock === 0) return 'stock-empty';
  if (stock <= 5) return 'stock-low';
  return 'stock-normal';
};

// 跳转到商品详情
const navigateToDetail = (product: Product) => {
  // 检查设备状态，如果离线则显示提示
  if (deviceInfo.value.status !== 2) {
    let message = '';
    switch (deviceInfo.value.status) {
      case 0: message = '设备未使用'; break;
      case 1: message = '设备离线'; break;
      case 3: message = '设备故障'; break;
      case 4: message = '设备维护中'; break;
      case 5: message = '设备待维护'; break;
      default: message = '设备不可用'; break;
    }
    uni.showToast({
      title: `${message}，无法查看详情`,
      icon: 'none',
      duration: 2000
    });
    return;
  }
  // 构建商品详情数据
  const productDetail = {
    id: product.id,
    name: product.name,
    price: product.price,
    mainImage: product.mainImage,
    stock: product.stock,
    channelId: product.channelId,
    channelPosition: product.channelPosition,
    quantity: 1,
    channelNo: product.channelNo
  };
  
  uni.navigateTo({
    url: `/pages/product/detail?product=${encodeURIComponent(JSON.stringify(productDetail))}&from=device&deviceNo=${deviceNo.value}`,
  });
};

// 生成订单号（如：ORD202506130030）
const generateOrderNo = () => {
  const now = new Date();
  const pad = (n) => n.toString().padStart(2, '0');
  const dateStr = [
    now.getFullYear(),
    pad(now.getMonth() + 1),
    pad(now.getDate()),
    pad(now.getHours()),
    pad(now.getMinutes())
  ].join('');
  const rand = Math.floor(Math.random() * 100).toString().padStart(2, '0');
  return 'ORD' + dateStr + rand;
};

// 立即购买
const buyNow = async (productId?: number) => {
  // 如果正在加载中，直接返回
  if (isLoading.value) {
    return;
  }
  
  try {
    isLoading.value = true;
    
    // 检查设备状态
    if (deviceInfo.value.status !== 2) {
      let message = '';
      switch (deviceInfo.value.status) {
        case 0: message = '设备未使用，无法购买'; break;
        case 1: message = '设备离线，无法购买'; break;
        case 3: message = '设备故障，无法购买'; break;
        case 4: message = '设备维护中，无法购买'; break;
        case 5: message = '设备待维护，无法购买'; break;
        default: message = '设备不可用，无法购买'; break;
      }
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      });
      isLoading.value = false;
      return;
    }

    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo) {
      uni.showToast({ title: '请先登录', icon: 'none' });
      isLoading.value = false;
      return;
    }

    let orderItems = [];
    let totalAmount = 0;
    let actualAmount = 0;
    let discountAmount = 0;
    let checkStockList = [];

    if (productId) {
      const product = products.value.find(p => p.id === productId);
      if (!product) {
        uni.showToast({ title: '商品不存在', icon: 'none', duration: 2000 });
        isLoading.value = false;
        return;
      }
      if (product.stock <= 0) {
        uni.showToast({ title: '商品库存不足', icon: 'none', duration: 2000 });
        isLoading.value = false;
        return;
      }
      orderItems = [{
        productId: product.id,
        productName: product.name,
        productImage: product.mainImage,
        channelNo: String(product.channelNo),
        channelPosition: product.channelPosition,
        price: product.price,
        quantity: 1,
        subtotal: product.price,
        status: 0
      }];
      totalAmount = product.price;
      actualAmount = calculateDiscountedPrice(product.price, selectedCoupon.value);
      discountAmount = totalAmount - actualAmount;
      
      // 添加库存检测项
      checkStockList.push({
        deviceId: deviceInfo.value.id,
        channelId: product.channelId,
        productId: product.id,
        stock: 1
      });
    } else {
      if (cartItems.value.length === 0) {
        uni.showToast({ title: '请先选择商品', icon: 'none', duration: 2000 });
        isLoading.value = false;
        return;
      }
      orderItems = cartItems.value.map(item => {
        const product = products.value.find(p => p.id === item.id);
        return {
          productId: item.id,
          productName: item.name,
          productImage: item.mainImage,
          channelNo: String(item.channelNo),
          channelPosition: item.channelPosition,
          price: item.price,
          quantity: item.quantity,
          subtotal: item.price * item.quantity,
          status: 0
        };
      });
      totalAmount = originalCartTotal.value;
      actualAmount = cartTotal.value;
      discountAmount = totalAmount - actualAmount;
      
      // 添加库存检测项
      checkStockList = cartItems.value.map(item => ({
        deviceId: deviceInfo.value.id,
        channelId: item.channelId,
        productId: item.id,
        stock: item.quantity
      }));
    }

    const orderNo1 = generateOrderNo();
    // 组装OrderBo
    const orderBo = {
      orderNo: orderNo1, // 生成订单号
      userId: userInfo.id,
      deviceId: deviceInfo.value.id,
      totalAmount,
      actualAmount,
      discountAmount,
      payType: 1, // 默认微信
      status: 0, // 待支付
      remark: '',
      orderDetail: orderItems, // 传数组，兼容单商品和多商品
      orderCoupon: selectedCoupon.value ? {
        userCouponId: selectedCoupon.value.id,
        couponId: selectedCoupon.value.couponId,
        couponCode: selectedCoupon.value.couponCode,
        couponName: selectedCoupon.value.couponName,
        couponType: selectedCoupon.value.coupon.type,
        discountAmount: discountAmount
      } : undefined
    };

    
    // 调用库存检测并创建订单接口
    const res = await checkStock(checkStockList, orderBo);
    
    if (res.code === 200) {
      
      // 如果使用了优惠券，更新用户优惠券状态
      if (selectedCoupon.value) {
        try {
          // 更新用户优惠券状态
          const userCouponData = {
            id: selectedCoupon.value.id,
            userId: userInfo.id,
            couponId: selectedCoupon.value.couponId,
            couponCode: selectedCoupon.value.couponCode,
            status: 1, // 已使用
            orderNo: orderNo1,
            useTime: formatDateTime(new Date())
          };
          await updateUserCoupon(userCouponData);
        } catch (couponError) {
          console.log('订单优惠券创建失败', couponError);
          isLoading.value = false;
          uni.showToast({ title: '优惠券创建失败', icon: 'none' });
          return;
        }
      }
      
      // 先关闭加载状态
      isLoading.value = false;
      
      uni.showToast({ title: '下单成功', icon: 'success' });
      // 跳转到订单详情页并传递订单号
      uni.navigateTo({
        url: `/pages/orders/create?deviceNo=${deviceNo.value}&cart=${encodeURIComponent(JSON.stringify(cartItems.value))}&originalTotal=${originalCartTotal.value}&payTotal=${cartTotal.value}&discountAmount=${(originalCartTotal.value-cartTotal.value)}&coupon=${selectedCoupon.value ? encodeURIComponent(JSON.stringify(selectedCoupon.value)) : ''}&orderNo=${orderNo1}`
      });
      
      // 在页面跳转后清空购物车数据
      setTimeout(() => {
        cartItems.value = [];
        selectedCoupon.value = null;
        saveCartToStorage();
      }, 100);
    } else {
      isLoading.value = false;
      uni.showToast({ title: res.msg || '下单失败', icon: 'none' });
    }
  } catch (e) {
    console.log('下单异常', e);
    isLoading.value = false;
    uni.showToast({ title: e.msg ||'下单异常', icon: 'none' });
  }
};

// 加载更多（由于使用设备信息中的库存，不需要分页）
const loadMore = () => {
  console.log('无需加载更多，使用设备信息中的库存数据');
};

// 图片加载错误处理
const onImageError = () => {
  console.log('设备图片加载失败');
};

const onProductImageError = () => {
  console.log('商品图片加载失败');
};

// 获取设备卡片样式类
const getDeviceCardClass = (status: number) => {
  switch (status) {
    case 0: return 'device-card-unused';
    case 1: return 'device-card-offline';
    case 2: return 'device-card-online';
    case 3: return 'device-card-error';
    case 4: return 'device-card-maintenance';
    case 5: return 'device-card-pending';
    default: return 'device-card-unused';
  }
};

// 获取商品卡片样式类
const getProductCardClass = (product: Product) => {
  if (product.stock === 0) return 'product-card-empty';
  if (product.stock <= 5) return 'product-card-low';
  return 'product-card-normal';
};

// 获取通道状态样式类
const getChannelStatusClass = (status: number) => {
  switch (status) {
    case 1: return 'channel-normal';
    case 2: return 'channel-warning';
    case 3: return 'channel-error';
    default: return 'channel-normal';
  }
};

// 获取通道状态文本
const getChannelStatusText = (status: number) => {
  switch (status) {
    case 1: return '正常';
    case 2: return '维护';
    case 3: return '故障';
    default: return '未知';
  }
};

// 获取正常通道数量
const getNormalChannelCount = () => {
  if (!deviceInfo.value.deviceChannel) return 0;
  return deviceInfo.value.deviceChannel.filter((channel: any) => channel.status === 1).length;
};

// 检查商品是否为低库存（仅用于显示标签）
const isLowStock = (product: Product) => {
  return product.stock <= 5 && product.stock > 0;
};

// 检查是否可以购买
const canBuy = () => {
  // 只有在线状态(2)且商品有库存时才能购买
  // 设备状态：0-未使用, 1-离线, 2-在线, 3-故障, 4-维护中, 5-待维护
  return deviceInfo.value.status === 2 && products.value.some(product => product.stock > 0);
};

// 获取购买按钮样式类
const getBuyButtonClass = () => {
  if (!canBuy()) return 'buy-btn-disabled';
  return 'buy-btn-normal';
};

// 获取购买按钮文本
const getBuyButtonText = () => {
  switch (deviceInfo.value.status) {
    case 0: return '设备未使用';
    case 1: return '设备离线';
    case 2: 
      if (!products.value.some(product => product.stock > 0)) {
        return '暂无库存';
      }
      return '立即购买';
    case 3: return '设备故障';
    case 4: return '维护中';
    case 5: return '待维护';
    default: return '设备不可用';
  }
};

// 购物车操作方法
const addToCart = (product: Product) => {
  // 检查设备状态
  if (deviceInfo.value.status !== 2) {
    let message = '';
    switch (deviceInfo.value.status) {
      case 0: message = '设备未使用'; break;
      case 1: message = '设备离线'; break;
      case 3: message = '设备故障'; break;
      case 4: message = '设备维护中'; break;
      case 5: message = '设备待维护'; break;
      default: message = '设备不可用'; break;
    }
    uni.showToast({
      title: `${message}，无法添加商品`,
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 检查库存
  if (product.stock <= 0) {
    uni.showToast({
      title: '商品库存不足',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 使用商品ID和通道ID组合作为唯一标识
  const cartItemId = `${product.id}-${product.channelId}`;
  const existingItem = cartItems.value.find(item => `${item.id}-${item.channelId}` === cartItemId);
  if (existingItem) {
    // 检查是否超过库存
    if (existingItem.quantity >= product.stock) {
      uni.showToast({
        title: '已达到最大库存数量',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    existingItem.quantity++;
  } else {
    cartItems.value.push({
      id: product.id,
      name: product.name,
      price: product.price,
      mainImage: product.mainImage,
      stock: product.stock,
      quantity: 1,
      channelId: product.channelId,
      channelNo: product.channelNo,
      channelPosition: product.channelPosition
    });
  }
  
  checkCouponAvailability();
  saveCartToStorage();
};

const removeFromCart = (productId: number, channelId: number) => {
  const index = cartItems.value.findIndex(item => item.id === productId && item.channelId === channelId);
  if (index > -1) {
    cartItems.value.splice(index, 1);
  }
  checkCouponAvailability();
  saveCartToStorage();
};

const updateCartQuantity = (productId: number, channelId: number, quantity: number) => {
  const item = cartItems.value.find(item => item.id === productId && item.channelId === channelId);
  if (item) {
    if (quantity <= 0) {
      removeFromCart(productId, channelId);
    } else if (quantity > item.stock) {
      uni.showToast({
        title: '不能超过库存数量',
        icon: 'none',
        duration: 2000
      });
    } else {
      item.quantity = quantity;
      saveCartToStorage();
    }
  }
  checkCouponAvailability();
};

const clearCart = () => {
  cartItems.value = [];
  selectedCoupon.value = null;
  uni.showToast({
    title: '购物车已清空',
    icon: 'success',
    duration: 1500
  });
  checkCouponAvailability();
  saveCartToStorage();
};

const toggleCart = () => {
  showCart.value = !showCart.value;
};

const buyFromCart = async () => {
  if (cartItems.value.length === 0) {
    uni.showToast({
      title: '请先选择商品',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
  // 检查设备状态
  if (deviceInfo.value.status !== 2) {
    let message = '';
    switch (deviceInfo.value.status) {
      case 0: message = '设备未使用，无法购买'; break;
      case 1: message = '设备离线，无法购买'; break;
      case 3: message = '设备故障，无法购买'; break;
      case 4: message = '设备维护中，无法购买'; break;
      case 5: message = '设备待维护，无法购买'; break;
      default: message = '设备不可用，无法购买'; break;
    }
    uni.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 调用buyNow函数，不传productId参数，这样会使用购物车中的商品创建订单
  await buyNow();
};

// 获取优惠券列表
const getCoupons = async () => {
  try {
    isLoadingCoupons.value = true;
    const userInfo = uni.getStorageSync('userInfo');
    if (!userInfo) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    const res = await getUserCouponList({
      pageNum: 1,
      pageSize: 100,
      userId: userInfo.id,
      status: 0 // 只获取未使用的优惠券
    });
    if (res.code === 200 && res.rows) {
      coupons.value = res.rows || [];
    }
  } catch (error) {
    console.error('获取优惠券失败：', error);
    uni.showToast({
      title: '获取优惠券失败',
      icon: 'none'
    });
  } finally {
    isLoadingCoupons.value = false;
  }
};

// 计算优惠后的价格
const calculateDiscountedPrice = (originalPrice: number, coupon: Coupon | null) => {
  if (!coupon) return originalPrice;
  
  // 检查是否满足最低消费金额
  if (coupon.coupon.minPoint && originalPrice < coupon.coupon.minPoint) {
    return originalPrice;
  }
  
  // 获取符合条件的商品总价
  const eligibleItemsTotal = cartItems.value.reduce((total, item) => {
    const product = products.value.find(p => p.id === item.id);
    if (!product) return total;
    
    // 检查商品是否满足优惠券使用条件
    let isEligible = false;
    switch (coupon.coupon.useScope) {
      case 0: // 全场通用
        isEligible = true;
        break;
      case 1: // 指定品类
        const categoryIds = coupon.coupon.scopeId.split(',').map(id => parseInt(id));
        isEligible = categoryIds.includes(product.categoryId || 0);
        break;
      case 2: // 指定商品
        const productIds = coupon.coupon.scopeId.split(',').map(id => parseInt(id));
        isEligible = productIds.includes(item.id);
        break;
    }
    
    return isEligible ? total + (item.price * item.quantity) : total;
  }, 0);
  
  // 如果符合条件的商品总价不满足最低消费要求，返回原价
  if (coupon.coupon.minPoint && eligibleItemsTotal < coupon.coupon.minPoint) {
    return originalPrice;
  }
  
  // 计算符合条件的商品优惠后的价格
  let discountedEligibleTotal = eligibleItemsTotal;
  switch (coupon.coupon.type) {
    case 1: // 满减券
      discountedEligibleTotal = Math.max(0, eligibleItemsTotal - coupon.coupon.discount);
      break;
    case 2: // 折扣券
      discountedEligibleTotal = Number((eligibleItemsTotal * coupon.coupon.discount).toFixed(2));
      break;
    case 3: // 立减券
      discountedEligibleTotal = Math.max(0, eligibleItemsTotal - coupon.coupon.discount);
      break;
  }
  
  // 计算不符合条件的商品总价
  const ineligibleItemsTotal = originalPrice - eligibleItemsTotal;
  
  // 返回总价（符合条件的商品优惠后价格 + 不符合条件的商品原价）
  return Number((discountedEligibleTotal + ineligibleItemsTotal).toFixed(2));
};

// 获取优惠券类型名称和描述
const getCouponTypeName = (type: number) => {
  switch (type) {
    case 1: return '满减券';
    case 2: return '折扣券';
    case 3: return '立减券';
    default: return '优惠券';
  }
};

// 获取优惠券详细描述
const getCouponDescription = (coupon: Coupon) => {
  if (!coupon) return '';
  
  const type = coupon.coupon.type;
  const discount = coupon.coupon.discount;
  const minPoint = coupon.coupon.minPoint;
  
  switch (type) {
    case 1: // 满减券
      return `满${minPoint}减${discount}`;
    case 2: // 折扣券
      return `${discount}折`;
    case 3: // 立减券
      return `立减${discount}`;
    default:
      return '';
  }
};

// 检查优惠券是否可用
const isCouponAvailable = (coupon: Coupon, amount: number) => {
  // 检查优惠券状态
  if (coupon.status !== 0) return false;
  
  // 检查有效期
  const now = new Date().getTime();
  const expireTime = new Date(coupon.expireTime).getTime();
  if (now > expireTime) return false;
  
  // 获取符合条件的商品总价
  const eligibleItemsTotal = cartItems.value.reduce((total, item) => {
    const product = products.value.find(p => p.id === item.id);
    if (!product) return total;
    
    // 检查商品是否满足优惠券使用条件
    let isEligible = false;
    switch (coupon.coupon.useScope) {
      case 0: // 全场通用
        isEligible = true;
        break;
      case 1: // 指定品类
        const categoryIds = coupon.coupon.scopeId.split(',').map(id => parseInt(id));
        isEligible = categoryIds.includes(product.categoryId || 0);
        break;
      case 2: // 指定商品
        const productIds = coupon.coupon.scopeId.split(',').map(id => parseInt(id));
        isEligible = productIds.includes(item.id);
        break;
    }
    
    return isEligible ? total + (item.price * item.quantity) : total;
  }, 0);
  
  // 检查最低使用金额
  if (coupon.coupon.minPoint && eligibleItemsTotal < coupon.coupon.minPoint) return false;
  
  // 只要有一个商品满足条件就返回true
  return eligibleItemsTotal > 0;
};

// 监听购物车变化，检查优惠券是否仍然可用
const checkCouponAvailability = () => {
  if (selectedCoupon.value && !isCouponAvailable(selectedCoupon.value, originalCartTotal.value)) {
    selectedCoupon.value = null;
    uni.showToast({
      title: '优惠券已失效，请重新选择',
      icon: 'none'
    });
  }
};

// 获取优惠券使用范围描述
const getCouponScopeDescription = (coupon: Coupon) => {
  switch (coupon.coupon.useScope) {
    case 0:
      return '全场通用';
    case 1:
      const categoryIds = coupon.coupon.scopeId.split(',');
      return `指定品类(${categoryIds.length}个)`;
    case 2:
      const productIds = coupon.coupon.scopeId.split(',');
      return `指定商品(${productIds.length}个)`;
    default:
      return '未知范围';
  }
};

// 选择优惠券
const selectCoupon = (coupon: Coupon) => {
  if (!isCouponAvailable(coupon, originalCartTotal.value)) {
    let message = '';
    if (coupon.coupon.minPoint && originalCartTotal.value < coupon.coupon.minPoint) {
      message = `订单金额未满足${coupon.coupon.minPoint}元使用条件`;
    } else {
      message = '优惠券不可用';
    }
    uni.showToast({
      title: message,
      icon: 'none'
    });
    return;
  }
  
  selectedCoupon.value = coupon;
  showCouponModal.value = false;
  
  // 显示优惠信息
  const discountAmount = originalCartTotal.value - calculateDiscountedPrice(originalCartTotal.value, coupon);
  uni.showToast({
    title: `已优惠¥${discountAmount.toFixed(2)}`,
    icon: 'success'
  });
  saveCartToStorage();
};

// 取消选择优惠券
const cancelCoupon = () => {
  selectedCoupon.value = null;
  showCouponModal.value = false;
  saveCartToStorage();
};

// 获取优惠券状态名称
const getCouponStatusName = (status: number) => {
  switch (status) {
    case 0: return '未使用';
    case 1: return '已使用';
    case 2: return '已过期';
    default: return '未知';
  }
};

// 显示优惠券选择弹窗
const showCouponSelector = () => {
  getCoupons();
  showCouponModal.value = true;
};

// 页面加载
onLoad((options: any) => {
  if (options?.deviceNo) {
    deviceNo.value = options.deviceNo;
    getDeviceInfo();
  } else {
    console.error('设备编号不能为空');
    uni.showToast({
      title: '设备编号不能为空',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
  loadCartFromStorage();
});

// 页面显示时刷新购物车
onShow(() => {
  loadCartFromStorage();
  getDeviceInfo();
});
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120px;
}

.device-info-card {
  background-color: #fff;
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
  margin-bottom: 10px;
}

.device-card-normal {
  border-left: 4px solid #52c41a;
}

.device-card-warning {
  border-left: 4px solid #faad14;
}

.device-card-error {
  border-left: 4px solid #ff4d4f;
}

.device-card-unused {
  border-left: 4px solid #d9d9d9;
}

.device-card-offline {
  border-left: 4px solid #bfbfbf;
}

.device-card-online {
  border-left: 4px solid #52c41a;
}

.device-card-maintenance {
  border-left: 4px solid #faad14;
}

.device-card-pending {
  border-left: 4px solid #1890ff;
}

.device-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.device-icon {
  width: 50px;
  height: 50px;
  margin-right: 15px;
  background-color: #f0f0f0;
  border-radius: 8px;
}

.device-title {
  flex: 1;
}

.device-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 5px;
}

.status-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.device-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  color: #fff;
}

.device-type-tag {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 8px;
  background-color: #f0f0f0;
  color: #666;
}

.status-normal {
  background-color: #52c41a;
}

.status-warning {
  background-color: #faad14;
}

.status-error {
  background-color: #ff4d4f;
}

.status-unused {
  background-color: #d9d9d9;
  color: #666;
}

.status-offline {
  background-color: #bfbfbf;
  color: #666;
}

.status-online {
  background-color: #52c41a;
}

.status-maintenance {
  background-color: #faad14;
}

.status-pending {
  background-color: #1890ff;
}

.location-info {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 15px;
}

.location-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.location-icon {
  font-size: 14px;
  margin-right: 5px;
}

.location-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.location-address {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.device-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 15px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  min-height: 40px;
}

.detail-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.detail-value {
  font-size: 13px;
  color: #333;
  font-weight: 500;
  word-break: break-all;
  line-height: 1.3;
}

.channel-overview {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 15px;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.overview-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.overview-count {
  font-size: 12px;
  color: #52c41a;
  font-weight: 500;
}

.channel-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 6px;
}

.channel-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 6px;
  border-radius: 6px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  min-height: 50px;
}

.channel-normal {
  border-color: #52c41a;
  background-color: #f6ffed;
}

.channel-warning {
  border-color: #faad14;
  background-color: #fffbe6;
}

.channel-error {
  border-color: #ff4d4f;
  background-color: #fff2f0;
}

.channel-position {
  font-size: 11px;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.channel-status {
  font-size: 9px;
  color: #666;
}

.online {
  color: #52c41a;
}

.offline {
  color: #ff4d4f;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  margin: 10px 10px 0 10px;
  border-radius: 12px 12px 0 0;
  border-bottom: 1px solid #f0f0f0;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.product-count {
  font-size: 14px;
  color: #999;
}

.product-list {
  background-color: #fff;
  margin: 0 10px;
  border-radius: 0 0 12px 12px;
  padding-bottom: 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 15px;
}

.empty-text {
  color: #999;
  font-size: 16px;
}

.products-container {
  display: flex;
  flex-wrap: wrap;
  margin: -6px;
  padding: 10px;
  padding-bottom: 20px;
}

.product-item {
  width: calc(50% - 6px);
  padding: 6px;
  box-sizing: border-box;
}

.product-item-content {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  height: 280px;
  transition: all 0.3s ease;
  position: relative;
}

.product-card-normal {
  border: 1px solid #e8e8e8;
}

.product-card-low {
  border: 1px solid #faad14;
  background-color: #fffbe6;
}

.product-card-empty {
  border: 1px solid #ff4d4f;
  background-color: #fff2f0;
  opacity: 0.6;
}

.product-item-content:active {
  transform: scale(0.96);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 150px;
  display: block;
  background-color: #f8f8f8;
  object-fit: cover;
}

.product-info {
  flex: 1;
  padding: 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 40px;
  margin-bottom: 8px;
}

.product-price-row {
  display: flex;
  align-items: baseline;
  margin-bottom: 8px;
}

.product-price {
  font-size: 16px;
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 4px;
}

.product-original-price {
  font-size: 11px;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: auto;
}

.meta-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tag-row {
  display: flex;
  gap: 4px;
}

.stock-info {
  font-weight: 500;
}

.stock-normal {
  color: #52c41a;
}

.stock-low {
  color: #faad14;
}

.stock-empty {
  color: #ff4d4f;
}

.hot-tag {
  display: inline-block;
  padding: 2px 6px;
  background: linear-gradient(135deg, #ff6b6b, #ff4d4f);
  color: #fff;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 500;
  box-shadow: 0 1px 4px rgba(255, 77, 79, 0.3);
}

.low-stock-tag {
  display: inline-block;
  padding: 2px 6px;
  background: linear-gradient(135deg, #ffa940, #faad14);
  color: #fff;
  border-radius: 8px;
  font-size: 10px;
  font-weight: 500;
  box-shadow: 0 1px 4px rgba(250, 173, 20, 0.3);
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 12px 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  border-top: 1px solid #eee;
  z-index: 1000;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-toggle-btn {
  width: 50px;
  height: 50px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  position: relative;
  transition: all 0.3s ease;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-toggle-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.cart-icon {
  font-size: 24px;
  color: #fff;
}

.cart-count {
  position: absolute;
  top: 5px;
  left: 12%;
  background-color: #ff4d4f;
  color: #fff;
  font-size: 12px;
  font-weight: bold;
  min-width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  border-radius: 10px;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.coupon-btn {
  flex: 1;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ffd700, #ffa500);
  border: none;
  border-radius: 25px;
  box-shadow: 0 4px 12px rgba(255, 165, 0, 0.3);
  transition: all 0.3s ease;
  padding: 0 20px;
  position: relative;
  overflow: hidden;
}

.coupon-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(255, 165, 0, 0.2);
}

.coupon-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transform: translateX(-100%);
  transition: transform 0.6s;
}

.coupon-btn:active::after {
  transform: translateX(100%);
}

.coupon-icon {
  font-size: 20px;
  margin-right: 8px;
}

.coupon-text {
  font-size: 15px;
  color: #fff;
  font-weight: 600;
  line-height: 20px;
}

.buy-now-btn {
  flex: 1;
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-radius: 25px;
  font-size: 16px;
  font-weight: bold;
  border: none;
  transition: all 0.3s ease;
}

.buy-btn-normal {
  background: linear-gradient(135deg, #ff6b6b, #ff4d4f);
  color: #fff;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
}

.buy-btn-disabled {
  background: linear-gradient(135deg, #d9d9d9, #bfbfbf);
  color: #999;
  box-shadow: none;
}

.buy-now-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.2);
}

.cart-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.cart-content {
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  padding: 24px;
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.1);
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.cart-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 36px;
  height: 36px;
  line-height: 36px;
  margin: 0px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: none;
  background-color: #f5f5f5;
  color: #666;
  font-size: 16px;
  transition: all 0.2s ease;
}

.close-btn:active {
  background-color: #e8e8e8;
  transform: scale(0.95);
}

.cart-items {
  margin-bottom: 24px;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 12px;
  background-color: #fafafa;
  border-radius: 12px;
  border: 1px solid #f0f0f0;
  transition: all 0.2s ease;
}

.cart-item:active {
  transform: scale(0.98);
  background-color: #f5f5f5;
}

.cart-item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 12px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.cart-item-info {
  flex: 1;
  min-width: 0;
}

.cart-item-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 4px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.cart-item-price {
  font-size: 14px;
  color: #ef4444;
  font-weight: 600;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 6px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 20px;
  padding: 4px;
  border: 1px solid #e9ecef;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: none;
  background-color: #fff;
  color: #333;
  font-size: 14px;
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  padding: 0;
}

.quantity-btn:active {
  transform: scale(0.95);
}

.quantity-text {
  font-size: 14px;
  color: #333;
  font-weight: 600;
  margin: 0 8px;
  min-width: 20px;
  text-align: center;
  line-height: 1;
}

.remove-icon {
  width: 16px;
  height: 16px;
  display: block;
}

.remove-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: none;
  background-color: #ef4444;
  color: #fff;
  transition: all 0.2s ease;
  padding: 0;
}

.remove-btn:active {
  transform: scale(0.95);
  background-color: #dc2626;
}

.cart-empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
}

.empty-text {
  color: #999;
  font-size: 16px;
  margin-top: 16px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.cart-total {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.total-label {
  margin-right: 8px;
}

.total-price {
  font-size: 24px;
  color: #ef4444;
  font-weight: bold;
}

.cart-actions {
  display: flex;
  gap: 16px;
}

.clear-btn {
  padding: 12px 24px;
  border-radius: 20px;
  border: none;
  background-color: #f5f5f5;
  color: #666;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.2s ease;
  min-width: 80px;
  height: 44px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clear-btn:active {
  background-color: #e8e8e8;
  transform: scale(0.95);
}

.buy-cart-btn {
  padding: 12px 32px;
  border-radius: 20px;
  border: none;
  background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
  color: #fff;
  font-size: 15px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
  transition: all 0.2s ease;
  min-width: 120px;
  height: 44px;
  line-height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.buy-cart-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
}

.channel-info {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.coupon-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.coupon-content {
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  padding: 24px;
  width: 100%;
  max-height: 70vh;
  overflow-y: auto;
  box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.1);
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.coupon-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.coupon-item {
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #fff5f5, #fff0f6);
  border: 1px solid #ffd6e7;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
}

.coupon-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transform: translateX(-100%);
  transition: transform 0.6s;
}

.coupon-item:active::before {
  transform: translateX(100%);
}

.coupon-header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.coupon-name {
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.coupon-type {
  font-size: 12px;
  color: #ff4d4f;
  background-color: #fff1f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.coupon-code {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.coupon-time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.coupon-get-time,
.coupon-expire-time {
  font-size: 12px;
  color: #999;
}

.coupon-status {
  padding-left: 15px;
  border-left: 1px dashed #ffd6e7;
  min-width: 60px;
  text-align: center;
}

.status-text {
  font-size: 13px;
  color: #52c41a;
  font-weight: 500;
}

.coupon-disabled {
  background: linear-gradient(135deg, #f5f5f5, #f0f0f0);
  border-color: #d9d9d9;
  opacity: 0.6;
}

.coupon-disabled::after {
  content: '不可用';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(-45deg);
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 4px 20px;
  font-size: 12px;
  border-radius: 4px;
}

.coupon-selected {
  background: linear-gradient(135deg, #e6f7ff, #bae7ff);
  border-color: #1890ff;
}

.coupon-selected::after {
  content: '已选择';
  position: absolute;
  top: 10px;
  right: 10px;
  background: #1890ff;
  color: #fff;
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 10px;
}

.empty-coupons {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.loading-coupons {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.coupon-value {
  margin: 8px 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.value-text {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
}

.min-point {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.coupon-scope {
  margin-bottom: 8px;
}

.scope-text {
  font-size: 12px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}
</style> 